import {CACHE_EXPIRES_TIME, CACHE_TOKEN, CACHE_USERINFO, FILE_REQUEST_URL} from './../config.js';
import Status from './status.js';

const qqMapWX = require('qqmap-wx-jssdk.min.js');
// const qqMapKey = "CUNBZ-N7MR2-6EJUP-CAHQA-CGFLH-UWBE6"
const qqMapKey = "RBABZ-2LRCD-MDB4N-HJBUA-WNZD7-NFFCJ"

const formatTime = (type, value = null, m) => {

  if (typeof type == 'undefined') {
    type = 0;
  }

  let date = null;
  if (value) {
    date = new Date(value);
  } else {
    date = new Date();
  }

  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();
  const hour = date.getHours();
  const minute = date.getMinutes();
  const second = date.getSeconds();

  if (type === 1) {
    return [year, month, day].map(formatNumber).join('-');
  } else if (type === 2) {
    return [year, month].map(formatNumber).join('-');
  } else if (type === 3) {
    return year + "年" + month + "月" + day + "日";
  } else if (type === 4) {
    return month + "月" + day + "日";
  } else if (type === 5) { //时分
    return hour + ":" + (minute < 10 ? ('0' + minute) : minute);
  } else if (type === 6) {
    return year + "." + (month < 10 ? ('0' + month) : month) + "." + (day < 10 ? ('0' + day) : day);
  }

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':');
};

/**
 * 指定日期前后
 * @param type 1: 后一天 0：前一天
 * @returns {string}
 */
function preNextDate(current_date, type = 0) {
  // Util.timeToDate(6)
  if (!current_date) {
    current_date = Util.formatTime(6);
  }
  current_date = current_date.replaceAll('.', "-")
  // console.log("current_date : " + current_date);
  //当前时间戳
  let currentTimeTimestamp = new Date(current_date).getTime()

  if (type == 1) {//后一天
    currentTimeTimestamp = currentTimeTimestamp + 24 * 60 * 60 * 1000
  } else { // 前一天
    currentTimeTimestamp = currentTimeTimestamp - 24 * 60 * 60 * 1000
  }

  const date = new Date(currentTimeTimestamp)
  const Year = date.getFullYear()
  const Month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
  const Day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
  // const Hour = date.getHours() < 10 ? '0' + date.getHours() : date.getHours();

  return Year + "." + Month + "." + Day;
}

const timeToDate = (value, type = 0) => {
  if (!value) return ""
  value = value * 1000;

  const date = new Date(parseInt(value));
  const year = date.getFullYear();
  const mon = date.getMonth() + 1;
  const day = date.getDate();
  const hour = date.getHours();
  const minute = date.getMinutes();
  const second = date.getSeconds();

  if (type == 1) {
    return (mon < 10 ? '0' : '') + mon + '-' + (day < 10 ? '0' : '') + day;
  } else if (type == 2) {
    return year + '/' + mon + '/' + day + " " + hour + ":" + (minute < 10 ? ('0' + minute) : minute);
  } else if (type == 3) {
    return mon + '/' + day;
  } else {
    return year + '/' + mon + '/' + day;
  }

};

const formatDate = (value, type = 0) => {
  if (!value) return ""
  var year = value.substring(2, 4);

  if (type == 1) { //年月
    return value.substring(2, 7);
  } else if (type == 2) { //月日 小时:分钟
    return value.substring(5, 16);
  } else if (type == 3) {
    return value.substring(5, 10);
  } else if (type == 4) {//年月日 小时:分钟
    return value.substring(2, 16);
  } else if (type == 5) {//年月日
    return value.substring(2, 10);
  } else if (type == 6) {//年月日 (yyyy-mm-dd)
    return value.substring(0, 10);
  } else if (type == 7) {//年 (yyyy)
    return value.substring(0, 4);
  }

  return year;
};

// 判断空
const isEmpty = (value) => {
  if (value === null || value === "" || value === "undefined" || value === undefined || value === "null") {
    return true;
  } else {
    if (typeof value === "string") {
      value = value.replace(/\s/g, "");
    } else if (typeof value === "object" && Object.keys(value).length == 0) {
      return true;
    }
    return value === "";
  }
}

const $h = {
  // 除法函数，用来得到精确的除法结果
  // 说明：javascript的除法结果会有误差，在两个浮点数相除的时候会比较明显。这个函数返回较为精确的除法结果。
  // 调用：$h.Div(arg1,arg2)
  // 返回值：arg1除以arg2的精确结果
  Div: function (arg1, arg2) {
    arg1 = parseFloat(arg1);
    arg2 = parseFloat(arg2);
    let t1 = 0, t2 = 0, r1, r2;
    try {
      t1 = arg1.toString().split('.')[1].length;
    } catch (e) {
      //console.log(e);
    }
    try {
      t2 = arg2.toString().split('.')[1].length;
    } catch (e) {
      //console.log(e);
    }
    r1 = Number(arg1.toString().replace('.', ''));
    r2 = Number(arg2.toString().replace('.', ''));
    return this.Mul(r1 / r2, Math.pow(10, t2 - t1));
  },
  // 加法函数，用来得到精确的加法结果
  // 说明：javascript的加法结果会有误差，在两个浮点数相加的时候会比较明显。这个函数返回较为精确的加法结果。
  // 调用：$h.Add(arg1,arg2)
  // 返回值：arg1加上arg2的精确结果
  Add: function (arg1, arg2) {
    arg2 = parseFloat(arg2);
    let r1, r2, m;
    try {
      r1 = arg1.toString().split('.')[1].length;
    } catch (e) {
      r1 = 0;
    }
    try {
      r2 = arg2.toString().split('.')[1].length;
    } catch (e) {
      r2 = 0;
    }
    m = Math.pow(100, Math.max(r1, r2));
    return (this.Mul(arg1, m) + this.Mul(arg2, m)) / m;
  },
  // 减法函数，用来得到精确的减法结果
  // 说明：javascript的加法结果会有误差，在两个浮点数相加的时候会比较明显。这个函数返回较为精确的减法结果。
  // 调用：$h.Sub(arg1,arg2)
  // 返回值：arg1减去arg2的精确结果
  Sub: function (arg1, arg2) {
    arg1 = parseFloat(arg1);
    arg2 = parseFloat(arg2);
    let r1, r2, m, n;
    try {
      r1 = arg1.toString().split('.')[1].length;
    } catch (e) {
      r1 = 0;
    }
    try {
      r2 = arg2.toString().split('.')[1].length;
    } catch (e) {
      r2 = 0;
    }
    m = Math.pow(10, Math.max(r1, r2));
    // 动态控制精度长度
    n = (r1 >= r2) ? r1 : r2;
    return ((this.Mul(arg1, m) - this.Mul(arg2, m)) / m).toFixed(n);
  },
  // 乘法函数，用来得到精确的乘法结果
  // 说明：javascript的乘法结果会有误差，在两个浮点数相乘的时候会比较明显。这个函数返回较为精确的乘法结果。
  // 调用：$h.Mul(arg1,arg2)
  // 返回值：arg1乘以arg2的精确结果
  Mul: function (arg1, arg2) {
    arg1 = parseFloat(arg1);
    arg2 = parseFloat(arg2);
    let m = 0, s1 = arg1.toString(), s2 = arg2.toString();
    try {
      m += s1.split('.')[1].length;
    } catch (e) {
      //console.log(e);
    }
    try {
      m += s2.split('.')[1].length;
    } catch (e) {
      //console.log(e);
    }
    return Number(s1.replace('.', '')) * Number(s2.replace('.', '')) / Math.pow(10, m);
  }
};

const formatNumber = (n) => {
  n = n.toString();
  return n[1] ? n : '0' + n;
};

/**
 * 处理服务器扫码带进来的参数
 * @param string param 扫码携带参数
 * @param string k 整体分割符 默认为：&
 * @param string p 单个分隔符 默认为：=
 * @return object
 *
 */
const getUrlParams = (param, k, p) => {
  if (typeof param != 'string') {
    return {};
  }
  k = k ? k : '&';// 整体参数分隔符
  p = p ? p : '=';// 单个参数分隔符
  const value = {};
  if (param.indexOf(k) !== -1) {
    param = param.split(k);
    for (const val in param) {
      if (param[val].indexOf(p) !== -1) {
        const item = param[val].split(p);
        value[item[0]] = item[1];
      }
    }
  } else if (param.indexOf(p) !== -1) {
    const item = param.split(p);
    value[item[0]] = item[1];
  } else {
    return param;
  }
  return value;
};

const wxgetUserInfo = function (data) {
  return new Promise((resolve, reject) => {
    wx.getUserProfile({
      desc: '业务需要',
      lang: 'zh_CN',
      success(res) {
        resolve(res);
      },
      fail(res) {
        reject(res);
      }
    });
  });
};

const showModelTip = function (content, title = "", confirmText = '', cancelText = "", showCancel = true) {
  return new Promise((resolve, reject) => {
    wx.showModal({
      title: title || '温馨提示',
      content: content,
      showCancel: showCancel,
      cancelText: cancelText || '取消',
      cancelColor: '#000000',
      confirmText: confirmText || '确定',
      confirmColor: '#239439',
      success: (res) => {
        resolve(res);
      },
      complete: () => {
        // isShowModal 解决安卓手机并发请求多次弹出wx.showModal的问题
        getApp().globalData.isShowModal = false;
      }
    })
  });
}

const checkLogin = function (token, expiresTime, isLog) {

  if (getApp()) {
    token = getApp().globalData.token;
    isLog = isLog == true ? isLog : getApp().globalData.isLog;
  }

  token = true;
  const res = !!token;
  const res1 = isLog;
  const res2 = res && res1;

  return res2;
};

const logout = function () {

  if (!isEmpty(getApp())) {
    getApp().globalData.token = '';
    getApp().globalData.isLog = false;
    getApp().globalData.userInfo = [];
  }

  const shared_id = wx.getStorageSync('shared_id');//分享会员
  const shop_id = wx.getStorageSync('shop_id');//分享会员

  wx.clearStorageSync();
  wx.clearStorage();
  wx.removeStorageSync('cache_key');

  if (shared_id) {
    wx.setStorageSync('shared_id', shared_id)
  }

  if (shop_id) {
    wx.setStorageSync('shop_id', shop_id)
  }

};

const chekWxLogin = function (type, scene) {

  if (type == 1) {
    logout();
  } else {
    //检测token 是否有效
    const token_expire_time = wx.getStorageSync(CACHE_EXPIRES_TIME);
    const current_timestamp = Date.parse(new Date()); //当前时间戳
    //缓存时间小于当前时间
    if (token_expire_time <= current_timestamp) {
      logout();
    }
  }

  return new Promise((resolve, reject) => {
    if (checkLogin()) {
      return resolve({
        userInfo: getApp().globalData.userInfo,
        isLogin: typeof getApp().globalData.userInfo.id != 'undefined'
      });
    }

    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.userInfo']) {
          wx.setStorageSync('is_logining', false)
          return reject({authSetting: false});
        } else {

          wx.getStorage({key: "USERINFO"}).then(res => {
            const userInfo = res.data ? JSON.parse(res.data) : "";
            return resolve({userInfo: userInfo, isLogin: isEmpty(userInfo.id) ? false : true});
          }).catch(errmsg => {

            if (wx.getStorageSync('is_logining')) {
              setTimeout(function () {
                chekWxLogin().then(res => {
                  return resolve({
                    userInfo: res.userInfo,
                  });
                });
              }, 500)
              return false;
            }
            wx.setStorageSync('is_logining', true)
            getCodeLogin((code) => {
              const sendData = {code: code.code};
              if (scene) {
                sendData.scene = scene;
              } else {
                sendData.scene = wx.getLaunchOptionsSync().scene;
              }

              sendData['client_version'] = __wxConfig.envVersion;
              sendData['share_id'] = wx.getStorageSync("shared_id")
              sendData['shop_id'] = wx.getStorageSync("shop_id")
              // sendData['elect_pool_id'] = wx.getStorageSync("elect_pool_id")
              // sendData['award_type'] = wx.getStorageSync("award_type") || 0
              // shop_id: wx.getStorageSync("shop_id"),

              wx.request({  // 登录信息
                url: getApp().globalData.url + '/api/login',
                method: 'POST',
                data: sendData,
                success: function (result) {
                  if (result.statusCode !== 200) {
                    reject(result.data.msg || "");
                    return
                  }
                  setUserCache(result);  // 保存cache
                  if (getCurrentPages().length > 0) {
                    wx.setStorageSync('is_login_refresh', 1)
                  }
                  wx.removeStorageSync("is_logining")

                  //判断是否有配送功能
                  if (!isEmpty(result.data.data)) {
                    wx.setStorageSync("is_deliver", result.data.data.is_deliver || 2);
                  }

                  return resolve({
                    userInfo: result.data.data,
                    isLogin: typeof result.data.data.id != 'undefined'
                  });
                },
                fail: function (res) {
                  wx.removeStorageSync("is_logining")
                  reject(res);
                }
              });
            });
          })
        }
      },
      fail(res) {
        return reject(res);
      }
    });

  });
};

const setUserCache = function (result, type = 0) {
  const app = getApp(),
    that = this,
    current_userInfo = result.data.data;
  let jessionid = result.header['Set-Cookie'];

  if (result.header['debug-cookie']) {
    wx.setStorageSync('JSESSIONID', 'SESSIONID=' + result.header['debug-cookie']);
  } else if (jessionid) {
    const start = jessionid.indexOf('SESSIONID');
    const end = jessionid.indexOf(';', start);
    jessionid = jessionid.substring(start, end);
    // 2 保存JESSIONID
    wx.setStorageSync('JSESSIONID', jessionid);
  }

  app.globalData.token = true;
  app.globalData.isLog = true;
  app.globalData.userInfo = current_userInfo || "";

  wx.setStorageSync(CACHE_TOKEN, true);
  wx.setStorageSync("cookie_token", current_userInfo.token || '');

  const expire_time = Date.parse(new Date()) + +23 * 3600 * 1000;
  wx.setStorageSync(CACHE_EXPIRES_TIME, expire_time);   //有效期 Token

  wx.setStorageSync(CACHE_USERINFO, JSON.stringify(current_userInfo));
  if (current_userInfo.cancel == 0) {//账户取消后直接跳转到恢复
    wx.redirectTo({
      url: '/pages/member/recover'
    })
  }
};

/**
 *
 * 授权过后自动登录
 */
const autoLogin = function () {
  return new Promise((resolve, reject) => {
    wx.getStorage({
      key: 'cache_key',
      success(res) {
        return resolve({userInfo: res.data, isLogin: false});
      },
      fail() {
        getCodeLogin((code) => {
          wx.request({  // 登录信息
            url: getApp().globalData.url + '/api/login',
            method: 'POST',
            header: {
              'cookie': wx.getStorageSync('JSESSIONID')
            },
            data: {
              code: code.code,
              shop_id: wx.getStorageSync("shop_id"),
            },
            success: function (result) {
              setUserCache(result);  // 保存cache
              return resolve({userInfo: result.data.data, isLogin: !!result.data.data.id});
            },
            fail: function (res) {
              return reject(res);
            }
          });
        });
      }
    });
  });
};

const getCodeLogin = function (successFn) {
  wx.login({
    success(res) {
      successFn(res);
    }
  });
};

/*
* 合并数组
*/
const SplitArray = function (list, sp) {
  if (typeof list != 'object') {
    return [];
  }
  if (sp === undefined) {
    sp = [];
  }

  for (let i = 0; i < list.length; i++) {
    sp.push(list[i]);
  }

  return sp;
};

/*
* 合并对象
*/
const SplitObject = function (list, sp) {
  if (typeof list !== 'object') {
    return {};
  }
  if (!list) {
    return sp;
  }
  if (sp === undefined) {
    sp = {};
  }

  for (const k in list) {
    if (typeof sp[k] === 'undefined') {
      sp[k] = list[k];
    }
  }

  return sp;
};

/**
 * opt  object | string
 * to_url object | string
 * 例:
 * this.Tips('/pages/test/test'); 跳转不提示
 * this.Tips({title:'提示'},'/pages/test/test'); 提示并跳转
 * this.Tips({title:'提示'},{tab:1,url:'/pages/index/index'}); 提示并跳转值table上
 * tab=1 一定时间后跳转至 table上
 * tab=2 一定时间后跳转至非 table上
 * tab=3 一定时间后返回上页面
 * tab=4 关闭所有页面跳转至非table上
 * tab=5 关闭当前页面跳转至非table页面
 */
const Tips = function (opt, to_url) {

  if (typeof opt == 'string') {
    to_url = opt;
    opt = {};
  }

  const title = opt.title || '', icon = opt.icon || 'none', endtime = opt.endtime || 2000;
  if (title) {
    wx.showToast({title: title, icon: icon, mask: !opt.hideMask, duration: endtime});
  }

  if (to_url != undefined) {
    if (typeof to_url == 'object') {
      const tab = to_url.tab || 1, url = to_url.url || '';
      switch (tab) {
        case 1:
          // 一定时间后跳转至 table
          setTimeout(function () {
            wx.switchTab({
              url: url
            });
          }, endtime);
          break;
        case 2:
          // 跳转至非table页面
          setTimeout(function () {
            wx.navigateTo({
              url: url
            });
          }, endtime);
          break;
        case 3:
          // 返回上页面
          setTimeout(function () {
            wx.navigateBack({
              delta: parseInt(url)
            });
          }, endtime);
          break;
        case 4:
          // 关闭当前所有页面跳转至非table页面
          setTimeout(function () {
            wx.reLaunch({
              url: url
            });
          }, endtime);
          break;
        case 5:
          // 关闭当前页面跳转至非table页面
          setTimeout(function () {
            wx.redirectTo({
              url: url
            });
          }, endtime);
          break;
      }

    } else if (typeof to_url == 'function') {
      setTimeout(function () {
        to_url && to_url();
      }, endtime);
    } else {
      // 没有提示时跳转不延迟
      setTimeout(function () {
        wx.navigateTo({
          url: to_url
        });
      }, title ? endtime : 0);
    }
  }
};


const getWxLocation = function () {
  let that = this;

  // 获取位置信息
  return new Promise((resolve, reject) => {
    const current_timestamp = Date.parse(new Date())
    /*
    let cache_sign = wx.getStorageSync("cache_sign_location");
    cache_sign = cache_sign ? JSON.parse(cache_sign) : []
    if (cache_sign && cache_sign.timestamp + 24 * 3600 * 1000 > current_timestamp) {
        wx.hideLoading()
        return resolve(cache_sign)
    } else {
        wx.setStorageSync("cache_sign_location", "");
    }
    */
    /* wx.showLoading({
       title: '正在获取位置',
     })*/
    wx.getLocation({
      type: 'gcj02',
      isHighAccuracy: true,
      highAccuracyExpireTime: 4000,
      success(res) {
        let precise_location = res;
        let qqmapsdk = new qqMapWX({
          key: qqMapKey
        });
        getLocation(qqmapsdk, precise_location.latitude, precise_location.longitude).then(res => {

          let address = "";
          if (res.address_component.nation === '中国') {
            address = res.address_component.province + " "
              + res.address_component.city + " "
              + res.address_component.district + " "
              + res.address_reference.town.title

            address += " " + res.address_component.street
            if (typeof res.formatted_addresses.recommend != 'undefined') {
              address += res.formatted_addresses.recommend.replace(res.address_component.city, "").replace(res.address_component.district, "").replace(res.address_reference.town.title, "")
            }
          }

          let result = {
            addressInfo: res,
            lat: precise_location.latitude,
            lng: precise_location.longitude,
            address: address,
            timestamp: current_timestamp
          }
          wx.hideLoading()
          wx.setStorageSync('cache_sign_location', JSON.stringify(result));
          resolve(result)
        }).catch(errmsg => {
          Tips({title: errmsg})
        })
        return
      },
      fail(res) {
        wx.hideLoading()
        wx.getSetting({
          success: function (res) {
            if (!res.authSetting['scope.userLocation']) {
              wx.showModal({
                title: '温馨提示',
                content: '需要使用你的位置，用于显示嘉宾距你的距离、推荐本地互选池以及本地脱单群。',
                confirmText: '授权',
                success: function (res) {
                  if (res.confirm) {
                    wx.openSetting();
                  } else {
                    console.log('get location fail');
                  }
                }
              })
            } else {
              //用户已授权，但是获取地理位置失败，提示用户去系统设置中打开定位
              wx.getSystemInfo({
                success: (res) => {
                  if (!res.locationEnabled || !res.locationAuthorized) {
                    wx.showModal({
                      title: '温馨提示',
                      content: '请在手机设置中开启微信定位功能，手机设置-应用设置-应用管理-找到微信-权限管理-定位-允许（不同型号手机可能有差异）',
                      showCancel: true,
                      cancelText: '取消',
                      cancelColor: '#000000',
                      confirmText: '朕知道了',
                      confirmColor: '#EF6243',
                      success: (res) => {
                        if (res.confirm) { // 提交屏蔽逻辑
                          console.log("hide")
                        }
                      },
                    })
                  }
                }
              })
            }
          }
        })

      }
    })
  })
}

// 检查是否开启位置
const checkOpenLocation = function () {
  return new Promise((resolve, reject) => {
    wx.getSetting({
      success: function (res) {
        if (res.authSetting['scope.userLocation'] != false) {
          getWxLocation().then(res => {
            res['open'] = 1;
            resolve(res)
          })
        } else {
          wx.showModal({
            title: '是否授权当前位置',
            content: '需要获取您的地理位置，请确认授权，否则将无法使用附近的人',
            success(res) {
              if (res.confirm) {
                wx.openSetting({
                  success(res) {
                    if (res.authSetting['scope.userLocation']) {
                      getWxLocation().then(res => {
                        res['open'] = 1;
                        resolve(res)
                      })
                    } else {
                      resolve({open: 0})
                    }
                  },
                  fail(res) {
                  }
                })
              } else {
                return Tips({title: "请在设置-应用-微信-权限中开启位置信息权限，以正常使用该功能"})
              }
            }
          })
        }
      }
    })
  })
}

/*
* 单图上传
* @param object opt
* @param callable successCallback 成功执行方法 data
* @param callable errorCallback 失败执行方法
*/
const uploadImageOne = function (opt, successCallback, errorCallback) {
  if (typeof opt === 'string') {
    const url = opt;
    opt = {};
    opt.url = url;
  }
  const count = opt.count || 1, sizeType = opt.sizeType || ['compressed'],
    sourceType = opt.sourceType || ['album', 'camera'],
    is_load = opt.is_load || true, uploadUrl = opt.url || '', inputName = opt.name || 'pics';

  wx.chooseImage({
    count: count,  // 最多可以选择的图片总数
    sizeType: sizeType, // 可以指定是原图还是压缩图，默认二者都有
    sourceType: sourceType, // 可以指定来源是相册还是相机，默认二者都有
    success: function (res) {
      // 启动上传等待中...
      wx.showLoading({title: '图片上传中'});
      wx.uploadFile({
        url: getApp().globalData.url + '/api/' + uploadUrl,
        filePath: res.tempFilePaths[0],
        name: 'file',
        formData: {
          'filename': inputName,
          'field_key': inputName
        },
        header: {'Content-Type': 'multipart/form-data'},
        success: function (res) {
          wx.hideLoading();
          if (res.statusCode == 403) {
            Tips({title: res.data});
          } else {
            const data = res.data ? JSON.parse(res.data) : {};
            if (data.status == 1) {
              successCallback && successCallback(data);
            } else {
              errorCallback && errorCallback(data);
              Tips({title: data.msg});
            }
          }
        }, fail: function (res) {
          wx.hideLoading();
          Tips({title: '上传图片失败'});
        }
      });
    }
  });
};

/**
 * 移除数组中的某个数组并组成新的数组返回
 * @param array array 需要移除的数组
 * @param int index 需要移除的数组的键值
 * @param string | int 值
 * @return array
 *
 */
const ArrayRemove = (array, index, value) => {
  const valueArray = [];
  if (array instanceof Array) {
    for (let i = 0; i < array.length; i++) {
      if (typeof index == 'number' && array[index] != i) {
        valueArray.push(array[i]);
      } else if (typeof index == 'string' && array[i][index] != value) {
        valueArray.push(array[i]);
      }
    }
  }
  return valueArray;
};

/**
 * 生成海报获取文字
 * @param string text 为传入的文本
 * @param int num 为单行显示的字节长度
 * @return array
 */
const textByteLength = (text, num) => {
  let strLength = 0;
  let rows = 1;
  let str = 0;
  const arr = [];
  for (let j = 0; j < text.length; j++) {
    if (text.charCodeAt(j) > 255) {
      strLength += 2;
      if (strLength > rows * num) {
        strLength++;
        arr.push(text.slice(str, j));
        str = j;
        rows++;
      }
    } else {
      strLength++;
      if (strLength > rows * num) {
        arr.push(text.slice(str, j));
        str = j;
        rows++;
      }
    }
  }
  arr.push(text.slice(str, text.length));
  return [strLength, arr, rows];   //  [处理文字的总字节长度，每行显示内容的数组，行数]
};

const getLocation = function (qqmap, lat, lng) {

  return new Promise((reslove, reject) => {
    qqmap.reverseGeocoder({
      location: {
        latitude: lat,
        longitude: lng
      },
      success: function (res) {
        if (typeof res.result.address_component != 'undefined') {
          reslove(res.result);
        } else {
          reject(res || '系统错误');
        }
      },
      fail: function (res) {
        reject(res.message || '系统错误');
      }
    });

  });
}

const checkPhone = (mobile) => {
  if (!(/1[3-9]\d{9}$/.test(mobile))) {
    // if(!preg_match('/^1[3-9][0-9]\d{8}$/', $mobile)){
    return false;
  }
  return true;
};

/**
 * 数字变动动画效果
 * @param float BaseNumber 原数字
 * @param float ChangeNumber 变动后的数字
 * @param object that 当前this
 * @param string name 变动字段名称
 * */
const AnimationNumber = (BaseNumber, ChangeNumber, that, name) => {
  const difference = $h.Sub(ChangeNumber, BaseNumber); // 与原数字的差
  const absDifferent = Math.abs(difference); // 差取绝对值
  const changeTimes = absDifferent < 6 ? absDifferent : 6; // 最多变化6次
  const changeUnit = absDifferent < 6 ? 1 : Math.floor(difference / 6);
  // 依次变化
  for (let i = 0; i < changeTimes; i += 1) {
    // 使用闭包传入i值，用来判断是不是最后一次变化
    (function (i) {
      setTimeout(() => {
        that.setData({
          [name]: $h.Add(BaseNumber, changeUnit)
        });
        // 差值除以变化次数时，并不都是整除的，所以最后一步要精确设置新数字
        if (i == changeTimes - 1) {
          that.setData({
            [name]: $h.Add(BaseNumber, difference)
          });
        }
      }, 100 * (i + 1));
    })(i);
  }
};

/**
 * 获取设备信息
 * @returns {Promise<any>}
 */
const wechatGetSystemInfo = function () {
  return new Promise((resolve, reject) => {
    wx.getSystemInfo({
      success: (res) => {
        resolve(res)
      }, fail: (err) => {
        reject(err)
      }
    })
  })
}

/**
 *  获取设备信息
 *  底部黑线适配
 */
const checkIphone = function () {
  return new Promise((resolve, reject) => {
    let isIphoneX = false

    wechatGetSystemInfo().then(res => {
      let modelmes = res.model;
      let iphoneArr = ['iPhone X', 'iPhone 11', 'iPhone 12', 'iPhone 13', 'iPhone 14', 'iPhone 15', 'iPhone 16']

      for (const key in iphoneArr) {
        if (modelmes.search(iphoneArr[key]) !== -1) {
          isIphoneX = true;
          break;
        }
      }
      resolve(isIphoneX)
    })
  })
  return isIphoneX
}

const isIphone = function () {
  return new Promise((resolve, reject) => {
    let isIphone = false
    wechatGetSystemInfo().then(res => {
      let modelmes = res.model;
      if (modelmes.search('iPhone') != -1 || modelmes.search('iPad') != -1 || modelmes.search('Mac') != -1) {
        isIphone = true;
      }
      resolve(isIphone)
    })
  })
  return isIphone
}

/**
 * 处理富文本里的图片宽度自适应
 * 1.去掉img标签里的style、width、height属性
 * 2.img标签添加style属性：max-width:100%;height:auto
 * 3.修改所有style里的width属性为max-width:100%
 * 4.去掉<br/>标签
 * @param html
 * @returns {void|string|*}
 */
function formatRichText(html) {
  let newContent = html.replace(/<img[^>]*>/gi, function (match, capture) {
    match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
    match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
    match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
    return match;
  });
  newContent = newContent.replace(/style="[^"]+"/gi, function (match, capture) {
    match = match.replace(/width:[^;]+;/gi, 'max-width:100%;').replace(/width:[^;]+;/gi, 'max-width:100%;');
    return match;
  });
  newContent = newContent.replace(/<br[^>]*\/>/gi, '');
  newContent = newContent.replace(/\<img/gi, '<img style="max-width:100%;height:auto;display:block;margin-top:0;margin-bottom:0;"');
  return newContent;
}

/**
 * params1： url
 * params2： 要获取参数
 */
const getQueryString = (url, name) => {
  var reg = new RegExp('(^|&|/?)' + name + '=([^&|/?]*)(&|/?|$)', 'i')
  var r = url.substr(1).match(reg)
  if (r != null) {
    return r[2]
  }
  return null;
}

/**
 * 获取当前页面带参数的路径
 * pages/elect-pool/my?share_id=5
 */
const getCurrentPath = () => {
  let userInfo = wx.getStorageSync(CACHE_USERINFO)
  userInfo = userInfo ? JSON.parse(userInfo) : [];//获取当前用户信息

  if (userInfo.length > 0)
    return false;

  var share_id = userInfo.id;//当前用户id
  if (isEmpty(share_id)) {
    return false;
  }
  wx.setStorageSync('share_id', share_id);
  var pages = getCurrentPages();//获取加载的页面
  var view = pages[pages.length - 1]; //获取当前页面的对象
  var options = Object.entries(view.options);//该页面参数
  var params = "?";//处理该页面的参数
  if (options.length > 0) {
    var newarr = SplitArray(options, [["share_id", share_id]]);//合并分享人参数
    newarr.forEach((elem, index) => {
      if (newarr.length - 1 == index) {
        params = params + elem[0] + "=" + elem[1];
      } else {
        params = params + elem[0] + "=" + elem[1] + "&";
      }
    });
  } else {
    params = params + "share_id=" + share_id;
  }
  if (userInfo.award_type == 1) {
    params = params + "&at=" + userInfo.award_type;
  }
  return view.route + params;//完整页面路径
};

const saveImg = function (url) {
  if (!url) return this.Tips({title: "图片地址必填"})
  var that = this;
  wx.downloadFile({
    url: url,
    success(res) {
      wx.saveImageToPhotosAlbum({
        filePath: res.tempFilePath,
        success(res) {
          return that.Tips({title: "保存成功", icon: "success"})
        },
        fail: res => {
          return that.Tips({title: "保存失败", icon: "error"})
        }
      })
    }
  })
}

/**
 * type   ： 1：不需要切图
 * @param image
 * @param width
 * @param height
 * @param type
 * @returns {string|boolean|*}
 */
const previewCdnImage = function (image, width = 0, height = 0, type = 0) {
  const img_domain = FILE_REQUEST_URL;

  if (!image || image.indexOf("http") >= 0) {
    return image;
  }

  /*if (!(empty($width) && empty($height))) {
    $image .= '?x-oss-process=image/resize,m_fill,';
  }

  if ($width && !$height) {
    return $image . 'w_' . $width;
  }

  if ($height && !$width) {
    return $image . 'h_' . $height;
  }

  if ($height && $width) {
    return $image . 'h_' . $height . ',w_' . $width;
  }*/
  let path = img_domain + image;
  if (!width && !height) {
    return img_domain + image;
  }
  path = path + '?x-oss-process=image/resize,m_fill,';
  if (width && !height) {
    return path + 'w_' + width;

    /* if (type)
       return img_domain + image + '?imageMogr2/thumbnail/' + width + 'x';
     return img_domain + image + '?imageMogr2/thumbnail/' + width + 'x' + '/scrop/' + width + 'x' + height + '/gravity/center';
  */
  }

  if (height && !width) {
    return path + 'h_' + height;
    /* if (type)
       return img_domain + image + '?imageMogr2/thumbnail/x' + height;

     return img_domain + image + '?imageMogr2/thumbnail/x' + height + '/scrop/' + width + 'x' + height + '/gravity/center';
   */
  }

  if (height && width) {
    return path + 'h_' + $height + ',w_' + $width;
    /*if (type)
      return img_domain + image + '?imageMogr2/scrop/' + width + 'x' + height;

    return img_domain + image + '?imageMogr2/scrop/' + width + 'x' + height + '/crop/' + width + 'x' + height + '/gravity/center';
  */
  }

  return false;
}

function outLink(url) {
  wx.navigateTo({
    url: "/pages/article/outlink?url=" + url
  })
}


/**
 * 判断路径是否是tabBar
 *   是 tabBar 返回 true
 * 不是 tabBar 返回 false
 */
function checkIsTabBar(url) {
  var arr = Status.tabbarMenus();
  for (const k in arr) {
    if (url == arr[k]['pagePath']) {
      return true;
    }
  }
  return false;
}

const checkIdcard = function (card) {
  const reg = /(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
  if (reg.test(card) == false) {
    return false;
  } else {
    return true;
  }
}

function checkIsChinese(val) {
  var reg = new RegExp("[\\u4E00-\\u9FFF]+", "g");
  if (reg.test(val) == false) {
    return false;
  } else {
    return true;
  }
}

/**
 * 获取用户当前所在的位置 【适应微信新版本获取地里位置信息，旧getLocation方法频繁调用有性能问题，并且30秒只能获得一次成功】
 */
const getSynLocation = () => {
  return new Promise((resolve, reject) => {
    const current_timestamp = Date.parse(new Date())
    let cache_sign = wx.getStorageSync("cache_sign_location");
    cache_sign = cache_sign ? JSON.parse(cache_sign) : []
    // 2 * 60
    if (cache_sign && cache_sign.timestamp + 10 * 60 * 1000 > current_timestamp) {
      cache_sign['is_cache'] = 1;
      return resolve(cache_sign)
    } else {
      wx.setStorageSync("cache_sign_location", "");
    }

    let _locationChangeFn = (res) => {
      // resolve(res) // 回传地里位置信息
      let precise_location = res;
      let qqmapsdk = new qqMapWX({
        key: qqMapKey
      });

      getLocation(qqmapsdk, precise_location.latitude, precise_location.longitude).then(res => {
        let address = ""
        if (res.address_component.nation === '中国') {
          address = res.address_component.province + " "
            + res.address_component.city + " "
            + res.address_component.district + " "
            + (res.address_reference.town.title || "");

          address += " " + res.address_component.street
          if (typeof res.formatted_addresses.recommend != 'undefined') {
            address += res.formatted_addresses.recommend.replace(res.address_component.city, "").replace(res.address_component.district, "").replace(res.address_reference.town.title, "")
          }
        }

        let result = {
          addressInfo: res,
          lat: precise_location.latitude,
          lng: precise_location.longitude,
          address: address,
          timestamp: current_timestamp
        }

        wx.hideLoading()
        wx.setStorageSync('cache_sign_location', JSON.stringify(result));
        resolve(result)
      }).catch(errmsg => {
        Tips({title: errmsg})
      })

      wx.offLocationChange(_locationChangeFn) // 关闭实时定位
      wx.stopLocationUpdate(_locationChangeFn); // 关闭监听 不关闭监听的话，有时获取位置时会非常慢
    }

    wx.getSetting({
      success: function (res) {
        if (res.authSetting['scope.userLocation'] != false) {

          getWxLocation().then(res => {
            /*
            res['open'] = 1;
            resolve(res)
            */
            wx.startLocationUpdate({
              success: (res) => {
                wx.onLocationChange(_locationChangeFn)
              },
              fail: (err) => {
                // 重新获取位置权限
                wx.openSetting({
                  success(res) {
                    res.authSetting = {
                      "scope.userLocation": true
                    }
                  }
                })
                reject(err)
              }
            })
          })

        } else {
          wx.showModal({
            title: '是否授权当前位置',
            content: '需要获取您的地理位置，请确认授权，否则将无法使用附近的人',
            success(res) {
              if (res.confirm) {
                wx.openSetting({
                  success(res) {
                    if (res.authSetting['scope.userLocation']) {
                      wx.startLocationUpdate({
                        success: (res) => {
                          wx.onLocationChange(_locationChangeFn)
                        },
                        fail: (err) => {
                          // 重新获取位置权限
                          wx.openSetting({
                            success(res) {
                              res.authSetting = {
                                "scope.userLocation": true
                              }
                            }
                          })
                          reject(err)
                        }
                      })
                    } else {
                      resolve({open: 0})
                    }
                  },
                  fail(res) {
                  }
                })
              } else {
                return Tips({title: "请在设置-应用-微信-权限中开启位置信息权限，以正常使用该功能"})
              }
            }
          })
        }
      }
    })
  })
}

/**
 * 获取实时经纬度
 * @returns {Promise}
 */
const getSynLocationLatlng = () => {
  return new Promise((resolve, reject) => {
    const current_timestamp = Date.parse(new Date())
    let cache_sign = wx.getStorageSync("cache_latlng_location");
    cache_sign = cache_sign ? JSON.parse(cache_sign) : []
    if (cache_sign && cache_sign.timestamp + 2 * 60 * 1000 > current_timestamp) {
      cache_sign['is_cache'] = 1;
      return resolve(cache_sign)
    } else {
      wx.setStorageSync("cache_latlng_location", "");
    }
    let _locationChangeFn = (res) => {
      resolve(res) // 回传地里位置信息

      let result = {
        // addressInfo: res,
        lat: res.latitude,
        lng: res.longitude,
        timestamp: current_timestamp
      }

      wx.setStorageSync('cache_latlng_location', JSON.stringify(result));
      wx.offLocationChange(_locationChangeFn) // 关闭实时定位
      wx.stopLocationUpdate(_locationChangeFn); // 关闭监听 不关闭监听的话，有时获取位置时会非常慢
    }
    wx.getSetting({
      success: function (res) {
        if (res.authSetting['scope.userLocation'] != false) {
          wx.startLocationUpdate({
            success: (res) => {
              wx.onLocationChange(_locationChangeFn)
            },
            fail: (err) => {
              // 重新获取位置权限
              wx.openSetting({
                success(res) {
                  res.authSetting = {
                    "scope.userLocation": true
                  }
                }
              })
              reject(err)
            }
          })
        } else {
          wx.showModal({
            title: '是否授权当前位置',
            content: '需要获取您的地理位置，请确认授权，否则将无法使用附近的人',
            success(res) {
              if (res.confirm) {
                wx.openSetting({
                  success(res) {
                    if (res.authSetting['scope.userLocation']) {
                      wx.startLocationUpdate({
                        success: (res) => {
                          wx.onLocationChange(_locationChangeFn)
                        },
                        fail: (err) => {
                          // 重新获取位置权限
                          wx.openSetting({
                            success(res) {
                              res.authSetting = {
                                "scope.userLocation": true
                              }
                            }
                          })
                          reject(err)
                        }
                      })
                    } else {
                      resolve({open: 0})
                    }
                  },
                  fail(res) {
                  }
                })
              } else {
                return Tips({title: "请在设置-应用-微信-权限中开启位置信息权限，以正常使用该功能"})
              }
            }
          })
        }
      }
    })
  })
}

// 解析扫码识别码
function getSceneParmas(scene) {
  if (!scene)
    return scene;

  scene = scene.split("-");
  if (scene[0] === "epqrcode") {//互选池
    return {
      id: scene[1],
      share_id: scene[2],
    }
  }

  if (scene[0] !== 'q')
    return scene;

  let data = [];
  for (const k in scene) {
    let v = scene[k].split("_");
    if (v.length === 1) {
      continue;
    }
    data[v[0]] = v[1];
  }

  if (!isEmpty(data)) {
    return data;
  }

  return scene;
}


function getWeek(value = null) {
  const weekDays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];

  let today = null;
  if (value) {
    today = new Date(value);
  } else {
    today = new Date();
  }
  const dayOfWeek = weekDays[today.getDay()];

  return dayOfWeek;
}

function getCartList(key = null) {
  // console.log("key: " + (key || "carts"))
  let cartList = wx.getStorageSync(key || "carts");
  // console.log(cartList)

  if (!isEmpty(cartList)) {
    cartList = cartList ? JSON.parse(cartList) : null;
    cartList = cartList.length == 0 ? null : cartList
  }

  return cartList || null;
}

/**
 * 去除数组空值
 * @param obj
 * @returns {*}
 */
function removeEmptyValues(obj) {
  for (const key in obj) {
    if (obj[key] === null || obj[key] === undefined) {
      delete obj[key];
    } else if (typeof obj[key] === 'object' && Object.keys(obj[key]).length === 0) {
      delete obj[key];
    }
  }
  return obj;
}

/**
 * 打电话
 * @param mobile
 */
function callPhone(mobile = null) {

  if (!mobile)
    return Tips({title: '手机号码错误', hideMask: true});

  wx.makePhoneCall({
    phoneNumber: mobile,
    success: function () {
    },
    fail: function () {
    }
  });
}

/**
 * 计算店铺配送价格
 * @param e
 * @returns {number}
 */
function getShopShippingPrice(amount = 0, base_shipping_price = null) {
  if (isEmpty(base_shipping_price) || amount == 0) {
    return 0;
  }

  let shipping_price = 0;
  base_shipping_price.map((e1) => {
    if (amount < e1.min || amount >= e1.max) {
      return true;
    }

    if (amount <= e1.max && e1.max > 0) {
      shipping_price = e1.total;
      return true;
    }

    shipping_price = e1.total;
    return true;
  })

  return parseFloat(shipping_price || 0);
}

/**
 * 格式化缓存
 * @param key
 * @returns {any|null}
 */
function getStorageInfo(key = null) {
  let info = wx.getStorageSync(key);
  if (!isEmpty(info)) {
    info = info ? JSON.parse(info) : null;
  }
  return info || null;
}

module.exports = {
  checkIsChinese: checkIsChinese,
  checkIdcard: checkIdcard,
  formatTime: formatTime,
  getWeek: getWeek,//周几
  formatNumber: formatNumber,
  checkPhone: checkPhone,
  Tips: Tips,
  showModelTip: showModelTip,
  uploadImageOne: uploadImageOne,
  SplitArray: SplitArray,
  SplitObject: SplitObject,

  ArrayRemove: ArrayRemove,
  getUrlParams: getUrlParams,
  getCodeLogin: getCodeLogin,
  chekWxLogin: chekWxLogin,
  checkLogin: checkLogin,
  wxgetUserInfo: wxgetUserInfo,
  getWxLocation: getWxLocation,
  logout: logout,

  wechatGetSystemInfo: wechatGetSystemInfo,
  checkIphone: checkIphone,
  isIphone: isIphone,
  getLocation: getLocation,
  formatRichText: formatRichText,
  isEmpty: isEmpty,
  timeToDate: timeToDate,
  formatDate: formatDate,

  getCurrentPath: getCurrentPath,
  previewCdnImage: previewCdnImage,
  checkOpenLocation: checkOpenLocation,
  outLink: outLink,

  sceneParams: getSceneParmas,
  getCartList: getCartList, //购物车数据

  callPhone: callPhone,
  getStorageInfo: getStorageInfo,
  preNextDate: preNextDate,
  getShopShippingPrice: getShopShippingPrice
};
